#ifndef _MAIN_W_
#define _MAIN_W_

#include <QApplication>
#include <QMainWindow>
#include <QKeyEvent>
#include <QPushButton>
#include <QMessageBox>
#include <QTimer>
#include <QThread>

class Worker : public QObject {
    Q_OBJECT
public slots:
    void startTimer() {
        QTimer *timer = new QTimer(this);
        connect(timer, &QTimer::timeout, this, &Worker::onTimeout);
        timer->start(3000); // 1 second interval
    }

    void onTimeout() {
        qDebug() << "Timeout in thread:" << QThread::currentThread();
        emit showDialog();
    }
    
Q_SIGNALS:
    void showDialog();
};

class MainWindow : public QMainWindow {
    Q_OBJECT

protected:
    void keyPressEvent(QKeyEvent *event) override {
        if (event->key() == Qt::Key_Escape) {
            qDebug() << "Escape key pressed";
            QApplication::quit();
        } else {
            qDebug() << "Key pressed:" << event->key();
        }
    }

    void keyReleaseEvent(QKeyEvent *event) override {
        qDebug() << "Key released:" << event->key();
    }

public:
    MainWindow(QWidget *parent = nullptr) : QMainWindow(parent) {
        setWindowTitle("Keyboard Event Example");
        resize(400, 300);
        
        button = new QPushButton("Press me", this);
        button->setGeometry(QRect(QPoint(100, 100), QSize(200, 50)));
        //QObject::connect(button, &QPushButton::clicked, this, &MainWindow::showDialog);
        
        QThread *workerThread = new QThread;
        Worker *worker = new Worker;
        worker->moveToThread(workerThread);
        QObject::connect(workerThread, &QThread::started, worker, &Worker::startTimer);
        QObject::connect(worker, &Worker::showDialog, this, &MainWindow::onShowDialog);
        workerThread->start();
    }
    
public slots:
    void onShowDialog() {
        qDebug() << "showDialog()";
        if (!isDialogOpen) {
            qDebug() << "showDialog() toshow";
            isDialogOpen = true;
            QMessageBox dialog;
            dialog.setText("This is a modal dialog");
            dialog.setModal(true);
            dialog.exec();
            isDialogOpen = false;
        }
        else {
            qDebug() << "showDialog() notshow";
        }
    }
    
    void myFunction() {
        qDebug() << "myFunction()";
        //showDialog();
    }
    
private:
    QPushButton *button;
    bool isDialogOpen = false;
};

#endif // _MAIN_W_